def equals(a,b):
    found=False
    same=True
    for ka,va in a.iteritems():
        for kb,vb in b.iteritems():
            if (ka==kb and vb!=va) or (ka!=kb and vb==va): same=False
            elif ka==kb and vb==va: found=True
    if found and same: return 1 #they are exactly the same
    elif found and not same: return 2 #they need updating
    else: return 3 #they have no relation at all
    
def init(sinks):
    print "initial sync (don't mess with anything)"
    for sink in sinks: sink.files=sink.get_files()
    files=[]
    for sink in sinks:
        for file in sink.files:
            for s in sinks:
                if s!=sink:
                    found=False
                    for f in s.files:
                        if equals(f,file)==1:
                            found=True
                        elif equals(f,file)==2:
                            print "removing %s from %s" % (f['title'], s.name)
                            s.remove(f)
                            s.files.remove(f)
                            print "creating %s from %s" % (file['title'],s.name)
                            s.create(file)
                            s.files.append(file)
                            found=True
                            continue
                    if not found:
                        print "creating %s to %s" % (file['title'],s.name)
                        s.create(file)
                        s.files.append(file)
    print "done. (ok to mess with stuff)"
def loop(sinks):
    print "loop"
    for sink in sinks:
        get_files=sink.get_files()
        
        #check if file deleted
        for file in sink.files:
            for f in get_files:
                if equals(file,f):
                    print file['title']
                    print f['title']
                    print "removing "+file['title']
                    for s in sinks:
                        if s!=sink:
                            print "         from "+s.name
                            s.remove(file)
                            sink.files.remove(file)

        #check if files added
        for file in get_files:
            for f in sink.files:
                if equals(file,f):
                    print "creating "+file['title']
                    for s in sinks:
                        if s!=sink:
                            print "         to "+s.name
                            s.create(file)
                            sink.files.append(file)

        #check if files modified